package com.wing.auth.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wing.common.exception.BusinessException;
import com.wing.redis.utils.redis.RedisHelperImpl;
import com.wing.auth.entity.request.GetTokenRequest;
import com.wing.auth.entity.response.GetTokenResponse;
import com.wing.auth.entity.response.TicketSendResponse;
import com.wing.set.entity.ChanjetSet;
import com.wing.set.service.ChanjetSetService;
import com.wing.util.ConstantsUtil;
import com.wing.util.HttpsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 畅捷通-应用授权
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Resource
    ChanjetSetService chanjetSetService;

    @Resource
    RedisHelperImpl redisHelper;

    @Override
    public TicketSendResponse appTicketSend() {

        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());
        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.TICKET_RESEND, headers, null);
        TicketSendResponse ticketSendResponse = JSON.parseObject(result, TicketSendResponse.class);
        return ticketSendResponse;
    }

    @Override
    public GetTokenResponse getToken() {
        //推送appTicket
//        TicketSendResponse ticketSendResponse = appTicketSend();
//        if (!"200".equals(ticketSendResponse.getCode())) {
//            throw new BusinessException("appTicket推送失败");
//        }
        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());

        GetTokenRequest getTokenRequest = new GetTokenRequest();
        //测试
        //getTokenRequest.setAppTicket(ConstantsUtil.APP_TICKET);
        //正式
        getTokenRequest.setAppTicket(redisHelper.getValue("appTicket").toString());
        getTokenRequest.setCertificate(chanjetSet.getAuthSecret());
        log.info("getToken print call back info appTicket:{}", redisHelper.getValue("appTicket"));

        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.GET_TOKEN, headers, JSON.toJSONString(getTokenRequest));
        GetTokenResponse getTokenResponse = JSON.parseObject(result, GetTokenResponse.class);
        if (!getTokenResponse.result) {
            throw new BusinessException("自建应用获取token失败:"+getTokenResponse.getError().getMsg());
        } else {
            //token写入redis缓存
            redisHelper.valuePut("chanjetToken", getTokenResponse.getValue().getAccessToken());
        }
        return getTokenResponse;
    }
}
